/*
    Copyright (C) 2010 Stuart Weston 

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

*/

#include <stdio.h>
#include <string.h>
#include <netdb.h>
/*	#include <linux/in.h>i*/
#include <sys/socket.h>
#include <unistd.h>


#define buflen 512
unsigned int portno = 2620;
char hostname[] = "156.62.231.188";

char *buf[buflen];     /* declare global to avoid stack */

main() 
   {
   int sd = socket(AF_INET, SOCK_STREAM, 0);  /* init socket descriptor */
   struct sockaddr_in sin;
   struct hostent *host = gethostbyname(hostname);
   char buf[buflen];
   char input[17];
   char message[17];
   int len;


   /*** PLACE DATA IN sockaddr_in struct ***/
   memcpy(&sin.sin_addr.s_addr, host->h_addr, host->h_length);
   sin.sin_family = AF_INET;
   sin.sin_port = htons(portno);

    /* Print out the intro */

    printf("mk5ctl : Version 0 Revision 0 - 20th Dec 2010\n");
    printf("This program comes with ABSOLUTELY NO WARRANTY.\n");
    printf("This is free software, and you are welcome to\n");
    printf("redistribute it under certain conditions.\n");
    printf("Check gpl-3.0.txt.\n");

   /*** CONNECT SOCKET TO THE SERVICE DESCRIBED BY sockaddr_in struct ***/
   if (connect(sd, (struct sockaddr *)&sin, sizeof(sin)) < 0)
     {
     	perror("error connecting");
     	return(1);
     }
   else
     {
     	printf("Connected\n\n");
     }

   sleep(1);   /* give server time to reply */

   while(strcmp(message,"exit\n\r")!=0)
     {
     /*char *message="status?\n\r";*/
     /* Get the command from the terminal */
     printf("mk5 >");
     scanf("%s",message);
     strcat(message,"\n\r");

     /* if its not exit, then send the command to the Mk5 */

     if(strcmp(message,"exit\n\r")!=0)
       {
        /* Send the command */
     	send(sd,message,strlen(message),0);

        /* Get the response */
     	recv(sd,buf,buflen,0);

        /* Print the response to the terminal */
     	printf("%s\n",buf);

       }
     }
   close(sd);
   }
